<?php

/*
 * [UCenter Home] (C) 2007-2008 Comsenz Inc. $Id: function_common.php 13519
 * 2010-01-05 02:42:46Z liguode $
 */

if (! defined('IN_UCHOME')) {
	exit('Access Denied');
}

// SQL ADDSLASHES
function saddslashes($string){
	if (is_array($string)) {
		foreach ( $string as $key => $val ) {
			$string[$key] = saddslashes($val);
		}
	} else {
		$string = addslashes($string);
	}
	return $string;
}

// 取消HTML代码
function shtmlspecialchars($string){
	if (is_array($string)) {
		foreach ( $string as $key => $val ) {
			$string[$key] = shtmlspecialchars($val);
		}
	} else {
		$string = preg_replace('/&amp;((#(\d{3,5}|x[a-fA-F0-9]{4})|[a-zA-Z][a-z0-9]{2,5});)/', '&\\1', str_replace(array(
				'&',
				'"',
				'<',
				'>'
		), array(
				'&amp;',
				'&quot;',
				'&lt;',
				'&gt;'
		), $string));
	}
	return $string;
}

// 字符串解密加密
function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0){
	
	$ckey_length = 4; // 随机密钥长度 取值 0-32;
	                  // 加入随机密钥，可以令密文无任何规律，即便是原文和密钥完全相同，加密结果也会每次不同，增大破解难度。
	                  // 取值越大，密文变动规律越大，密文变化 = 16 的 $ckey_length 次方
	                  // 当此值为 0 时，则不产生随机密钥
	
	$key = md5($key ? $key : UC_KEY);
	$keya = md5(substr($key, 0, 16));
	$keyb = md5(substr($key, 16, 16));
	$keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length) : substr(md5(microtime()), - $ckey_length)) : '';
	
	$cryptkey = $keya . md5($keya . $keyc);
	$key_length = strlen($cryptkey);
	
	$string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0) . substr(md5($string . $keyb), 0, 16) . $string;
	$string_length = strlen($string);
	
	$result = '';
	$box = range(0, 255);
	
	$rndkey = array();
	for($i = 0; $i <= 255; $i ++) {
		$rndkey[$i] = ord($cryptkey[$i % $key_length]);
	}
	
	for($j = $i = 0; $i < 256; $i ++) {
		$j = ($j + $box[$i] + $rndkey[$i]) % 256;
		$tmp = $box[$i];
		$box[$i] = $box[$j];
		$box[$j] = $tmp;
	}
	
	for($a = $j = $i = 0; $i < $string_length; $i ++) {
		$a = ($a + 1) % 256;
		$j = ($j + $box[$a]) % 256;
		$tmp = $box[$a];
		$box[$a] = $box[$j];
		$box[$j] = $tmp;
		$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
	}
	
	if ($operation == 'DECODE') {
		if ((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyb), 0, 16)) {
			return substr($result, 26);
		} else {
			return '';
		}
	} else {
		return $keyc . str_replace('=', '', base64_encode($result));
	}
}

// 数据库连接
function dbconnect(){
	global $_SGLOBAL, $_SC;
	
	include_once (S_ROOT . './api/class_mysql.php');
	
	if (empty($_SGLOBAL['db'])) {
		$_SGLOBAL['db'] = new dbstuff();
		$_SGLOBAL['db']->charset = $_SC['dbcharset'];
		$_SGLOBAL['db']->connect($_SC['dbhost'], $_SC['dbuser'], $_SC['dbpw'], $_SC['dbname'], $_SC['pconnect']);
	}
}

// 获取在线IP
function getonlineip($format = 0){
	global $_SGLOBAL;
	
	if (empty($_SGLOBAL['onlineip'])) {
		if (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
			$onlineip = getenv('HTTP_CLIENT_IP');
		} elseif (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
			$onlineip = getenv('HTTP_X_FORWARDED_FOR');
		} elseif (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
			$onlineip = getenv('REMOTE_ADDR');
		} elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
			$onlineip = $_SERVER['REMOTE_ADDR'];
		}
		preg_match("/[\d\.]{7,15}/", $onlineip, $onlineipmatches);
		$_SGLOBAL['onlineip'] = $onlineipmatches[0] ? $onlineipmatches[0] : 'unknown';
	}
	if ($format) {
		$ips = explode('.', $_SGLOBAL['onlineip']);
		for($i = 0; $i < 3; $i ++) {
			$ips[$i] = intval($ips[$i]);
		}
		return sprintf('%03d%03d%03d', $ips[0], $ips[1], $ips[2]);
	} else {
		return $_SGLOBAL['onlineip'];
	}
}

// 获取到表名
function tname($name){
	global $_SC;
	return $_SC['tablepre'] . $name;
}

// 添加数据
function inserttable($tablename, $insertsqlarr, $returnid = 0, $replace = false, $silent = 0){
	global $_SGLOBAL;
	
	$insertkeysql = $insertvaluesql = $comma = '';
	foreach ( $insertsqlarr as $insert_key => $insert_value ) {
		$insertkeysql .= $comma . '`' . $insert_key . '`';
		$insertvaluesql .= $comma . '\'' . $insert_value . '\'';
		$comma = ', ';
	}
	$method = $replace ? 'REPLACE' : 'INSERT';
	
	$_SGLOBAL['db']->query($method . ' INTO ' . tname($tablename) . ' (' . $insertkeysql . ') VALUES (' . $insertvaluesql . ')', $silent ? 'SILENT' : '');
	if ($returnid && ! $replace) {
		return $_SGLOBAL['db']->insert_id();
	}
}

// 更新数据
function updatetable($tablename, $setsqlarr, $wheresqlarr, $silent = 0){
	global $_SGLOBAL;
	
	$setsql = $comma = '';
	foreach ( $setsqlarr as $set_key => $set_value ) { // fix
		$setsql .= $comma . '`' . $set_key . '`' . '=\'' . $set_value . '\'';
		$comma = ', ';
	}
	$where = $comma = '';
	if (empty($wheresqlarr)) {
		$where = '1';
	} elseif (is_array($wheresqlarr)) {
		foreach ( $wheresqlarr as $key => $value ) {
			$where .= $comma . '`' . $key . '`' . '=\'' . $value . '\'';
			$comma = ' AND ';
		}
	} else {
		$where = $wheresqlarr;
	}
	$_SGLOBAL['db']->query('UPDATE ' . tname($tablename) . ' SET ' . $setsql . ' WHERE ' . $where, $silent ? 'SILENT' : '');
}

// 获得用户UID
function getuid($name){
	global $_SGLOBAL, $_SCONFIG;
	
	$wherearr[] = "(username='$name')";
	if ($_SCONFIG['realname']) {
		$wherearr[] = "(name='$name' AND namestatus = 1)";
	}
	$uid = 0;
	$query = $_SGLOBAL['db']->query("SELECT uid,username,name,namestatus FROM " . tname('space') . " WHERE " . implode(' OR ', $wherearr) . " LIMIT 1");
	if ($space = $_SGLOBAL['db']->fetch_array($query)) {
		$uid = $space['uid'];
	}
	return $uid;
}

// 获取字符串
function getstr($string, $length, $in_slashes = 0, $out_slashes = 0, $censor = 0, $bbcode = 0, $html = 0){
	global $_SC, $_SGLOBAL;
	
	$string = trim($string);
	
	if ($in_slashes) {
		// 传入的字符有slashes
		$string = sstripslashes($string);
	}
	if ($html < 0) {
		// 去掉html标签
		$string = preg_replace("/(\<[^\<]*\>|\r|\n|\s|\[.+?\])/is", ' ', $string);
		$string = shtmlspecialchars($string);
	} elseif ($html == 0) {
		// 转换html标签
		$string = shtmlspecialchars($string);
	}
	if ($censor) {
		// 词语屏蔽
		@ include_once (S_ROOT . './data/data_censor.php');
		if ($_SGLOBAL['censor']['banned'] && preg_match($_SGLOBAL['censor']['banned'], $string)) {
			showmessage('information_contains_the_shielding_text');
		} else {
			$string = empty($_SGLOBAL['censor']['filter']) ? $string : @ preg_replace($_SGLOBAL['censor']['filter']['find'], $_SGLOBAL['censor']['filter']['replace'], $string);
		}
	}
	if ($length && strlen($string) > $length) {
		// 截断字符
		$wordscut = '';
		if (strtolower($_SC['charset']) == 'utf-8') {
			// utf8编码
			$n = 0;
			$tn = 0;
			$noc = 0;
			while ( $n < strlen($string) ) {
				$t = ord($string[$n]);
				if ($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
					$tn = 1;
					$n ++;
					$noc ++;
				} elseif (194 <= $t && $t <= 223) {
					$tn = 2;
					$n += 2;
					$noc += 2;
				} elseif (224 <= $t && $t < 239) {
					$tn = 3;
					$n += 3;
					$noc += 2;
				} elseif (240 <= $t && $t <= 247) {
					$tn = 4;
					$n += 4;
					$noc += 2;
				} elseif (248 <= $t && $t <= 251) {
					$tn = 5;
					$n += 5;
					$noc += 2;
				} elseif ($t == 252 || $t == 253) {
					$tn = 6;
					$n += 6;
					$noc += 2;
				} else {
					$n ++;
				}
				if ($noc >= $length) {
					break;
				}
			}
			if ($noc > $length) {
				$n -= $tn;
			}
			$wordscut = substr($string, 0, $n);
		} else {
			for($i = 0; $i < $length - 1; $i ++) {
				if (ord($string[$i]) > 127) {
					$wordscut .= $string[$i] . $string[$i + 1];
					$i ++;
				} else {
					$wordscut .= $string[$i];
				}
			}
		}
		$string = $wordscut;
	}
	if ($bbcode) {
		include_once (S_ROOT . './api/function_bbcode.php');
		$string = bbcode($string, $bbcode);
	}
	if ($out_slashes) {
		$string = saddslashes($string);
	}
	return trim($string);
}

// 时间格式化
function sgmdate($dateformat, $timestamp = '', $format = 0){
	global $_SCONFIG, $_SGLOBAL;
	if (empty($timestamp)) {
		$timestamp = $_SGLOBAL['timestamp'];
	}
	$timeoffset = strlen($_SGLOBAL['member']['timeoffset']) > 0 ? intval($_SGLOBAL['member']['timeoffset']) : intval($_SCONFIG['timeoffset']);
	$result = '';
	if ($format) {
		$time = $_SGLOBAL['timestamp'] - $timestamp;
		if ($time > 24 * 3600) {
			$result = gmdate($dateformat, $timestamp + $timeoffset * 3600);
		} elseif ($time > 3600) {
			$result = intval($time / 3600) . lang('hour') . lang('before');
		} elseif ($time > 60) {
			$result = intval($time / 60) . lang('minute') . lang('before');
		} elseif ($time > 0) {
			$result = $time . lang('second') . lang('before');
		} else {
			$result = lang('now');
		}
	} else {
		$result = gmdate($dateformat, $timestamp + $timeoffset * 3600);
	}
	return $result;
}

// 字符串时间化
function sstrtotime($string){
	global $_SGLOBAL, $_SCONFIG;
	$time = '';
	if ($string) {
		$time = strtotime($string);
		if (gmdate('H:i', $_SGLOBAL['timestamp'] + $_SCONFIG['timeoffset'] * 3600) != date('H:i', $_SGLOBAL['timestamp'])) {
			$time = $time - $_SCONFIG['timeoffset'] * 3600;
		}
	}
	return $time;
}

// 分页
function multi($num, $perpage, $curpage, $mpurl, $page = 5){
	
	$multipage = '<div class="pagination" id="pagenavi">';
	$mpurl .= strpos($mpurl, '?') ? '&' : '?';
	$realpages = 1;
	if ($num > $perpage) {
		$offset = 2;
		$realpages = @ceil($num / $perpage);
		$pages = $realpages;
		if ($page > $pages) {
			$from = 1;
			$to = $pages;
		} else {
			$from = $curpage - $offset;
			$to = $from + $page - 1;
			if ($from < 1) {
				$to = $curpage + 1 - $from;
				$from = 1;
				if ($to - $from < $page) {
					$to = $page;
				}
			} elseif ($to > $pages) {
				$from = $pages - $page + 1;
				$to = $pages;
			}
		}
		$urlplus = '';
		if ($curpage - $offset > 1 && $pages > $page) {
			$multipage .= "<a ";
			
			$multipage .= "href=\"{$mpurl}page=1{$urlplus}\"";
			
			$multipage .= " class=\"first\">1 ...</a>";
		}
		if ($curpage > 1) {
			$multipage .= "<a ";
			
			$multipage .= "href=\"{$mpurl}page=" . ($curpage - 1) . "$urlplus\"";
			
			$multipage .= " class=\"prev\">&lsaquo;&lsaquo;</a>";
		}
		for($i = $from; $i <= $to; $i ++) {
			if ($i == $curpage) {
				$multipage .= '<span class="current">' . $i . '</span>';
			} else {
				$multipage .= "<a ";
				
				$multipage .= "href=\"{$mpurl}page=$i{$urlplus}\"";
				
				$multipage .= ">$i</a>";
			}
		}
		if ($curpage < $pages) {
			$multipage .= "<a ";
			
			$multipage .= "href=\"{$mpurl}page=" . ($curpage + 1) . "{$urlplus}\"";
			
			$multipage .= " class=\"next\">&rsaquo;&rsaquo;</a>";
		}
		if ($to < $pages) {
			$multipage .= "<a ";
			
			$multipage .= "href=\"{$mpurl}page=$pages{$urlplus}\"";
			
			$multipage .= " class=\"last\">... $realpages</a>";
		}
		if ($multipage) {
			$multipage .= '<label style="margin-left: 5px;">Total<span style="font-weight: bold;">' . $num . '</span></label>';
		}
	}
	$multipage .= '</div>';
	return $multipage;
}

// 处理分页
function smulti($start, $perpage, $count, $url, $ajaxdiv = ''){
	global $_SGLOBAL;
	
	$multi = array(
			'last' => - 1,
			'next' => - 1,
			'begin' => - 1,
			'end' => - 1,
			'html' => ''
	);
	if ($start > 0) {
		if (empty($count)) {
			showmessage('no_data_pages');
		} else {
			$multi['last'] = $start - $perpage;
		}
	}
	
	$showhtml = 0;
	if ($count == $perpage) {
		$multi['next'] = $start + $perpage;
	}
	$multi['begin'] = $start + 1;
	$multi['end'] = $start + $count;
	
	if ($multi['begin'] >= 0) {
		if ($multi['last'] >= 0) {
			$showhtml = 1;
			if ($_SGLOBAL['inajax']) {
				$multi['html'] .= "<a href=\"javascript:;\" onclick=\"ajaxget('$url&ajaxdiv=$ajaxdiv', '$ajaxdiv')\">|&lt;</a> <a href=\"javascript:;\" onclick=\"ajaxget('$url&start=$multi[last]&ajaxdiv=$ajaxdiv', '$ajaxdiv')\">&lt;</a> ";
			} else {
				$multi['html'] .= "<a href=\"$url\">|&lt;</a> <a href=\"$url&start=$multi[last]\">&lt;</a> ";
			}
		} else {
			$multi['html'] .= "&lt;";
		}
		$multi['html'] .= " $multi[begin]~$multi[end] ";
		if ($multi['next'] >= 0) {
			$showhtml = 1;
			if ($_SGLOBAL['inajax']) {
				$multi['html'] .= " <a href=\"javascript:;\" onclick=\"ajaxget('$url&start=$multi[next]&ajaxdiv=$ajaxdiv', '$ajaxdiv')\">&gt;</a> ";
			} else {
				$multi['html'] .= " <a href=\"$url&start=$multi[next]\">&gt;</a>";
			}
		} else {
			$multi['html'] .= " &gt;";
		}
	}
	
	return $showhtml ? $multi['html'] : '';
}

// ob
function obclean(){
	global $_SC;
	
	ob_end_clean();
	if ($_SC['gzipcompress'] && function_exists('ob_gzhandler')) {
		ob_start('ob_gzhandler');
	} else {
		ob_start();
	}
}

// 获取数目
function getcount($tablename, $wherearr = array (), $get = 'COUNT(*)'){
	global $_SGLOBAL;
	if (empty($wherearr)) {
		$wheresql = '1';
	} else {
		$wheresql = $mod = '';
		foreach ( $wherearr as $key => $value ) {
			$wheresql .= $mod . "`$key`='$value'";
			$mod = ' AND ';
		}
	}
	return $_SGLOBAL['db']->result($_SGLOBAL['db']->query("SELECT $get FROM " . tname($tablename) . " WHERE $wheresql LIMIT 1"), 0);
}

// 调整输出
function ob_out(){
	global $_SGLOBAL, $_SCONFIG, $_SC;
	
	$content = ob_get_contents();
	
	$preg_searchs = $preg_replaces = $str_searchs = $str_replaces = array();
	
	if ($_SCONFIG['allowrewrite']) {
		$preg_searchs[] = "/\<a href\=\"space\.php\?(uid|do)+\=([a-z0-9\=\&]+?)\"/ie";
		$preg_searchs[] = "/\<a href\=\"space.php\"/i";
		$preg_searchs[] = "/\<a href\=\"network\.php\?ac\=([a-z0-9\=\&]+?)\"/ie";
		$preg_searchs[] = "/\<a href\=\"network.php\"/i";
		
		$preg_replaces[] = 'rewrite_url(\'space-\',\'\\2\')';
		$preg_replaces[] = '<a href="space.html"';
		$preg_replaces[] = 'rewrite_url(\'network-\',\'\\1\')';
		$preg_replaces[] = '<a href="network.html"';
	}
	if ($_SCONFIG['linkguide']) {
		$preg_searchs[] = "/\<a href\=\"http\:\/\/(.+?)\"/ie";
		$preg_replaces[] = 'iframe_url(\'\\1\')';
	}
	
	if ($_SGLOBAL['inajax']) {
		$preg_searchs[] = "/([\x01-\x09\x0b-\x0c\x0e-\x1f])+/";
		$preg_replaces[] = ' ';
		
		$str_searchs[] = ']]>';
		$str_replaces[] = ']]&gt;';
	}
	
	if ($preg_searchs) {
		$content = preg_replace($preg_searchs, $preg_replaces, $content);
	}
	if ($str_searchs) {
		$content = trim(str_replace($str_searchs, $str_replaces, $content));
	}
	
	obclean();
	if ($_SGLOBAL['inajax']) {
		xml_out($content);
	} else {
		if ($_SCONFIG['headercharset']) {
			@ header('Content-Type: text/html; charset=' . $_SC['charset']);
		}
		// 生成静态文件
		html_doing($content);
		
		if (D_BUG) {
			@ include_once (S_ROOT . './api/inc_debug.php');
		}
	}
}

function xml_out($content){
	global $_SC;
	@ header("Expires: -1");
	@ header("Cache-Control: no-store, private, post-check=0, pre-check=0, max-age=0", FALSE);
	@ header("Pragma: no-cache");
	@ header("Content-type: application/xml; charset=$_SC[charset]");
	echo '<' . "?xml version=\"1.0\" encoding=\"$_SC[charset]\"?>\n";
	echo "<root><![CDATA[" . trim($content) . "]]></root>";
	exit();
}

// rewrite链接
function rewrite_url($pre, $para){
	$para = str_replace(array(
			'&',
			'='
	), array(
			'-',
			'-'
	), $para);
	return '<a href="' . $pre . $para . '.html"';
}

// 外链
function iframe_url($url){
	$url = rawurlencode($url);
	return "<a href=\"link.php?url=http://$url\"";
}

// 处理搜索关键字
function stripsearchkey($string){
	$string = trim($string);
	$string = str_replace('*', '%', addcslashes($string, '%_'));
	$string = str_replace('_', '\_', $string);
	return $string;
}

// 是否屏蔽二级域名
function isholddomain($domain){
	global $_SCONFIG;
	
	$domain = strtolower($domain);
	
	if (preg_match("/^[^a-z]/i", $domain))
		return true;
	$holdmainarr = empty($_SCONFIG['holddomain']) ? array(
			'www'
	) : explode('|', $_SCONFIG['holddomain']);
	$ishold = false;
	foreach ( $holdmainarr as $value ) {
		if (strpos($value, '*') === false) {
			if (strtolower($value) == $domain) {
				$ishold = true;
				break;
			}
		} else {
			$value = str_replace('*', '', $value);
			if (@ preg_match("/$value/i", $domain)) {
				$ishold = true;
				break;
			}
		}
	}
	return $ishold;
}

// 连接字符
function simplode($ids){
	return "'" . implode("','", $ids) . "'";
}

// 显示进程处理时间
function debuginfo(){
	global $_SGLOBAL, $_SC, $_SCONFIG;
	
	if (empty($_SCONFIG['debuginfo'])) {
		$info = '';
	} else {
		$mtime = explode(' ', microtime());
		$totaltime = number_format(($mtime[1] + $mtime[0] - $_SGLOBAL['supe_starttime']), 4);
		$info = 'Processed in ' . $totaltime . ' second(s), ' . $_SGLOBAL['db']->querynum . ' queries' . ($_SC['gzipcompress'] ? ', Gzip enabled' : NULL);
	}
	
	return $info;
}

// 格式化大小函数
function formatsize($size){
	$prec = 3;
	$size = round(abs($size));
	$units = array(
			0 => " B ",
			1 => " KB",
			2 => " MB",
			3 => " GB",
			4 => " TB"
	);
	if ($size == 0)
		return str_repeat(" ", $prec) . "0$units[0]";
	$unit = min(4, floor(log($size) / log(2) / 10));
	$size = $size * pow(2, - 10 * $unit);
	$digi = $prec - 1 - floor(log($size) / log(10));
	$size = round($size * pow(10, $digi)) * pow(10, - $digi);
	return $size . $units[$unit];
}

// 获取文件内容
function sreadfile($filename){
	$content = '';
	if (function_exists('file_get_contents')) {
		@ $content = file_get_contents($filename);
	} else {
		if (@ $fp = fopen($filename, 'r')) {
			@ $content = fread($fp, filesize($filename));
			@ fclose($fp);
		}
	}
	return $content;
}

// 写入文件
function swritefile($filename, $writetext, $openmod = 'w'){
	if (@ $fp = fopen($filename, $openmod)) {
		flock($fp, 2);
		fwrite($fp, $writetext);
		fclose($fp);
		return true;
	} else {
		//runlog('error', "File: $filename write error.");
		return false;
	}
}

// 产生随机字符
function random($length, $numeric = 0){
	PHP_VERSION < '4.2.0' ? mt_srand(( double ) microtime() * 1000000) : mt_srand();
	$seed = base_convert(md5(print_r($_SERVER, 1) . microtime()), 16, $numeric ? 10 : 35);
	$seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
	$hash = '';
	$max = strlen($seed) - 1;
	for($i = 0; $i < $length; $i ++) {
		$hash .= $seed[mt_rand(0, $max)];
	}
	return $hash;
}

// 判断字符串是否存在
function strexists($haystack, $needle){
	return ! (strpos($haystack, $needle) === FALSE);
}

// 获取数据
function data_get($var, $isarray = 0){
	global $_SGLOBAL;
	
	$query = $_SGLOBAL['db']->query("SELECT * FROM " . tname('data') . " WHERE var='$var' LIMIT 1");
	if ($value = $_SGLOBAL['db']->fetch_array($query)) {
		return $isarray ? $value : $value['datavalue'];
	} else {
		return '';
	}
}

// 更新数据
function data_set($var, $datavalue, $clean = 0){
	global $_SGLOBAL;
	
	if ($clean) {
		$_SGLOBAL['db']->query("DELETE FROM " . tname('data') . " WHERE var='$var'");
	} else {
		if (is_array($datavalue))
			$datavalue = serialize(sstripslashes($datavalue));
		$_SGLOBAL['db']->query("REPLACE INTO " . tname('data') . " (var, datavalue, dateline) VALUES ('$var', '" . addslashes($datavalue) . "', '$_SGLOBAL[timestamp]')");
	}
}

// 站点链接
function getsiteurl(){
	global $_SCONFIG;
	
	if (empty($_SCONFIG['siteallurl'])) {
		$uri = $_SERVER['REQUEST_URI'] ? $_SERVER['REQUEST_URI'] : ($_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME']);
		return shtmlspecialchars('http://' . $_SERVER['HTTP_HOST'] . substr($uri, 0, strrpos($uri, '/') + 1));
	} else {
		return $_SCONFIG['siteallurl'];
	}
}

// 获取文件名后缀
function fileext($filename){
	return strtolower(trim(substr(strrchr($filename, '.'), 1)));
}

// 去掉slassh
function sstripslashes($string){
	if (is_array($string)) {
		foreach ( $string as $key => $val ) {
			$string[$key] = sstripslashes($val);
		}
	} else {
		$string = stripslashes($string);
	}
	return $string;
}

// 编码转换
function siconv($str, $out_charset, $in_charset = ''){
	global $_SC;
	
	$in_charset = empty($in_charset) ? strtoupper($_SC['charset']) : strtoupper($in_charset);
	$out_charset = strtoupper($out_charset);
	if ($in_charset != $out_charset) {
		if (function_exists('iconv') && (@ $outstr = iconv("$in_charset//IGNORE", "$out_charset//IGNORE", $str))) {
			return $outstr;
		} elseif (function_exists('mb_convert_encoding') && (@ $outstr = mb_convert_encoding($str, $out_charset, $in_charset))) {
			return $outstr;
		}
	}
	return $str; // 转换失败
}

// 处理积分星星
function getstar($experience){
	global $_SCONFIG;
	
	$starimg = '';
	if ($_SCONFIG['starcredit'] > 1) {
		// 计算星星数
		$starnum = intval($experience / $_SCONFIG['starcredit']) + 1;
		if ($_SCONFIG['starlevelnum'] < 2) {
			if ($starnum > 10)
				$starnum = 10;
			for($i = 0; $i < $starnum; $i ++) {
				$starimg .= '<img src="image/star_level10.gif" align="absmiddle" />';
			}
		} else {
			// 计算等级(10个)
			for($i = 10; $i > 0; $i --) {
				$numlevel = intval($starnum / pow($_SCONFIG['starlevelnum'], ($i - 1)));
				if ($numlevel > 10)
					$numlevel = 10;
				if ($numlevel) {
					for($j = 0; $j < $numlevel; $j ++) {
						$starimg .= '<img src="image/star_level' . $i . '.gif" align="absmiddle" />';
					}
					break;
				}
			}
		}
	}
	if (empty($starimg))
		$starimg = '<img src="image/credit.gif" alt="' . $experience . '" align="absmiddle" alt="' . $experience . '" title="' . $experience . '" />';
	return $starimg;
}

// 重新组建
function renum($array){
	$newnums = $nums = array();
	foreach ( $array as $id => $num ) {
		$newnums[$num][] = $id;
		$nums[$num] = $num;
	}
	return array(
			$nums,
			$newnums
	);
}

// 整理feed的链接
function mktarget($html){
	global $_SCONFIG;
	
	if ($html && $_SCONFIG['feedtargetblank']) {
		$html = preg_replace("/<a(.+?)href=([\'\"]?)([^>\s]+)\\2([^>]*)>/i", '<a target="_blank" \\1 href="\\3" \\4>', $html);
	}
	return $html;
}

// 整理分享
function mkshare($share){
	$share['body_data'] = unserialize($share['body_data']);
	
	// body
	$searchs = $replaces = array();
	if ($share['body_data']) {
		foreach ( array_keys($share['body_data']) as $key ) {
			$searchs[] = '{' . $key . '}';
			$replaces[] = $share['body_data'][$key];
		}
	}
	$share['body_template'] = str_replace($searchs, $replaces, $share['body_template']);
	
	return $share;
}

// ip访问允许
function ipaccess($ipaccess){
	return empty($ipaccess) ? true : preg_match("/^(" . str_replace(array(
			"\r\n",
			' '
	), array(
			'|',
			''
	), preg_quote($ipaccess, '/')) . ")/", getonlineip());
}

// ip访问禁止
function ipbanned($ipbanned){
	return empty($ipbanned) ? false : preg_match("/^(" . str_replace(array(
			"\r\n",
			' '
	), array(
			'|',
			''
	), preg_quote($ipbanned, '/')) . ")/", getonlineip());
}

// 截取链接
function sub_url($url, $length){
	if (strlen($url) > $length) {
		$url = str_replace(array(
				'%3A',
				'%2F'
		), array(
				':',
				'/'
		), rawurlencode($url));
		$url = substr($url, 0, intval($length * 0.5)) . ' ... ' . substr($url, - intval($length * 0.3));
	}
	return $url;
}

// 取数组中的随机个
function sarray_rand($arr, $num = 1){
	$r_values = array();
	if ($arr && count($arr) > $num) {
		if ($num > 1) {
			$r_keys = array_rand($arr, $num);
			foreach ( $r_keys as $key ) {
				$r_values[$key] = $arr[$key];
			}
		} else {
			$r_key = array_rand($arr, 1);
			$r_values[$r_key] = $arr[$r_key];
		}
	} else {
		$r_values = $arr;
	}
	return $r_values;
}

// 获得用户唯一串
function space_key($space, $appid = 0){
	global $_SCONFIG;
	return substr(md5($_SCONFIG['sitekey'] . '|' . $space['uid'] . (empty($appid) ? '' : '|' . $appid)), 8, 16);
}

// 检查邮箱是否有效
function isemail($email){
	return strlen($email) > 6 && preg_match("/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/", $email);
}

// 获取目录
function sreaddir($dir, $extarr = array ()){
	$dirs = array();
	if ($dh = opendir($dir)) {
		while ( ($file = readdir($dh)) !== false ) {
			if (! empty($extarr) && is_array($extarr)) {
				if (in_array(strtolower(fileext($file)), $extarr)) {
					$dirs[] = $file;
				}
			} else if ($file != '.' && $file != '..') {
				$dirs[] = $file;
			}
		}
		closedir($dh);
	}
	return $dirs;
}

// 自定义分页
function mob_perpage($perpage){
	global $_SGLOBAL;
	
	$newperpage = isset($_GET['perpage']) ? intval($_GET['perpage']) : 0;
	if ($_SGLOBAL['mobile'] && $newperpage > 0 && $newperpage < 500) {
		$perpage = $newperpage;
	}
	return $perpage;
}

// 检查用户的特殊身份
function ckspacelog(){
}

// 逐级生成目录文件并赋权限,$path 必须为绝对路径
function create_dir($path){ // 创建目录
	global $_SGLOBAL;
	
	$dirs = dirname($path);
	if (is_dir($path))
		return;
	$dirs = explode('/', $dirs);
	
	// 判断操作系统，linux的话，去除第一空项
	if (strpos($path, '/') == 0) {
		$dirpath = '/';
		unset($dirs[0]);
	}
	
	while ( ($directory = array_shift($dirs)) ) {
		$dirpath .= $directory . '/';
		
		if (! is_dir($dirpath)) {
			mkdir($dirpath);
			if (! chmod($dirpath, 0777)) {
				$directory = false;
				break;
			}
		} else {
			$directory = true;
		}
	}
	
	return $directory;

}

function gethtmlpath($filename, $dirname, $mkdir = true){
	global $_SGLOBAL, $_SC;
	
	if (! preg_match("/(.*)\/$/", $dirname)) {
		$dirname .= "/";
	}
	$dirs = preg_replace("/(.*)\/$/", '\\1', $dirname);
	// $dirs = dirname($dirname);
	// echo is_dir($dirname);die();
	if (is_dir($dirs))
		return $dirname . $filename;
	
	$names = explode('/', $dirs);
	// print_r($names);die();
	if ($mkdir) {
		$newfilename = '';
		foreach ( $names as $v ) {
			$newfilename .= $v . '/';
			if (! is_dir($newfilename)) {
				if (! @ mkdir($newfilename)) {
					//runlog('error', "DIR: $newfilename can not make");
				}
			}
		}
	}
	return $newfilename . $filename;
}
// 获得后台语言
function cplang($key){
	return $key;
}
// 检查start
function ckstart($start, $perpage){
	global $_SGLOBAL;
	
	$maxstart = $perpage * intval($_SGLOBAL['maxpage']);
	if ($start < 0 || ($maxstart > 0 && $start >= $maxstart)) {
		die('length_is_not_within_the_scope_of');
	}
}
// pwmd5=md5('sess_picsave_'+pw+'y');
function checkAuth($email, $pwmd5){
	global $_SGLOBAL;
	$arr = array(
			"status" => 0,
			"msg" => "",//为xheditor服务
	);
	if (empty($email) || empty($pwmd5)) {
		$arr["err"] = "账号或者密码为空";
		return $arr;
	}
	
	$query = $_SGLOBAL['db']->query("SELECT * FROM " . tname('user') . " where email='$email' limit 1");
	$value = $_SGLOBAL['db']->fetch_array($query);
	if (empty($value)) {
		$arr["err"] = "账号不存在";
		return $arr;
	}
	// var_dump($value);exit;
	if ($value['password'] == $pwmd5) {
		switch ($value['status']) {
			case - 1 :
				$arr["err"] = "账号已经冻结";
				break;
			case 0 :
				$arr["err"] = "账号未激活";
				break;			
			case 1 :
				$arr["status"] = 1;
// 				$_SESSION["uid"] = $value['uid'];
// 				$_SESSION["username"] = $value['username'];
// 				$_SESSION["email"] = $email;
// 				$_SESSION["pwmd5"] = $pwmd5;			
				$value["pwmd5"] = $pwmd5;			
				$_SESSION["user"] = $value;
				$arr['user'] = $value;
				break;			
			default :
				$arr["err"] = "账号状态异常";
		}
		return $arr;
	}else{
		$arr["err"] = "账号或密码不正确";
		return $arr;
	}
}

function checklogin(){	
	return isset($_SESSION['user'])&&!empty($_SESSION['user']);
}


function unescape($str){
	$ret = '';
	$len = strlen($str);
	for ($i = 0; $i < $len; $i++){
		if ($str[$i] == '%' && $str[$i+1] == 'u'){
			$val = hexdec(substr($str, $i+2, 4));
			if ($val < 0x7f) $ret .= chr($val);
			else if($val < 0x800) $ret .= chr(0xc0|($val>>6)).chr(0x80|($val&0x3f));
			else $ret .= chr(0xe0|($val>>12)).chr(0x80|(($val>>6)&0x3f)).chr(0x80|($val&0x3f));
			$i += 5;
		}
		else if ($str[$i] == '%'){
			$ret .= urldecode(substr($str, $i, 3));
			$i += 2;
		}
		else $ret .= $str[$i];
	}
	return $ret;
}
function unescape_gb($str) {
	$str = rawurldecode($str);
	preg_match_all("/%u.{4}|&#x.{4};|&#d+;|.+/U",$str,$r);
	$ar = $r[0];
	foreach($ar as $k=>$v) {
		if(substr($v,0,2) == "%u")
			$ar[$k] = iconv("UCS-2","GBK",pack("H4",substr($v,-4)));
		elseif(substr($v,0,3) == "&#x")
		$ar[$k] = iconv("UCS-2","GBK",pack("H4",substr($v,3,-1)));
		elseif(substr($v,0,2) == "&#") {
			$ar[$k] = iconv("UCS-2","GBK",pack("n",substr($v,2,-1)));
		}
	}
	return join("",$ar);
}

?>
